package edu.scau.pos.refund.service;

import cn.hutool.core.util.IdUtil;
import edu.scau.core.Enum.RefundStatus;
import edu.scau.core.util.RedisCache;
import edu.scau.core.util.ServletUtils;
import edu.scau.pos.refund.domain.RefundRecord;
import edu.scau.pos.refund.domain.RefundRecordItem;
import edu.scau.pos.refund.mapper.RefundRecordMapper;
import edu.scau.pos.refund.vo.RefundRecordVo;
import edu.scau.system.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

@Service
@Slf4j
public class RefundRecordServiceImpl implements RefundRecordService{
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RefundRecordMapper refundRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCache(RefundRecord refundRecord) {
        String createBy = tokenService.getLoginUser(ServletUtils.getRequest()).getUsername();
        Date createTime = new Date();
        refundRecord.setCreateBy(createBy);
        refundRecord.setCreateTime(createTime);
        if(refundRecord.getRefundRecordItemList()!=null && refundRecord.getRefundRecordItemList().size()>0){
            int res=this.insertRefundRecordItems(refundRecord.getRefundRecordItemList());
            if(res==0 || res < refundRecord.getRefundRecordItemList().size()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                log.info("insertRefundRecordItems批量失败");
            }
        }
        return refundRecordMapper.addCache(refundRecord);

    }

    private int insertRefundRecordItems(List<RefundRecordItem> refundRecordItemList) {
        int sum=0;
        for (RefundRecordItem refundRecordItem : refundRecordItemList) {
            sum+=refundRecordMapper.insertRefundRecordItem(refundRecordItem);
        }
        return sum;
    }

    @Override
    public  List<RefundRecordVo> getRefundRecordsList() {
        return refundRecordMapper.listAll();
    }

    @Override
    public RefundRecord getRefundRecord(String refundId) {
        return refundRecordMapper.getRefundRecordItemByRefundId(refundId);
    }

    @Override
    public void deletedRefundRecord(String refundId) {
        return;
    }

    @Override
    public int addOrUpdateRefundRecord(RefundRecord refundRecord) {
        if(this.isExist(refundRecord.getRefundId())){
          return refundRecordMapper.updateRefundRecord(refundRecord);
        }
        return addCache(refundRecord);
    }

    @Override
    public boolean isExist(String refundId) {
        return refundRecordMapper.isExistRefundRecord(refundId)>0 ;
    }


}
